package com.sls.nzdapplication.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hjq.widget.view.ClearEditText;
import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.markfrain.formview.view.FormEditView;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.AppActivity;
import com.sls.nzdapplication.db.utils.DyEquipmentLineUtil;
import com.sls.nzdapplication.db.utils.DyEquipmentUtil;
import com.sls.nzdapplication.db.utils.MeterBoxUtil;
import com.sls.nzdapplication.db.utils.MeterUtil;
import com.sls.nzdapplication.db.utils.SwitchEquipmentUtil;
import com.sls.nzdapplication.db.utils.SwitchUtil;
import com.sls.nzdapplication.model.DyEquipment;
import com.sls.nzdapplication.model.DyEquipmentLine;
import com.sls.nzdapplication.model.Meter;
import com.sls.nzdapplication.model.MeterBox;
import com.sls.nzdapplication.model.Switch;
import com.sls.nzdapplication.model.SwitchEquipment;
import com.sls.nzdapplication.ui.custom.CableWellPhotoView;
import com.sls.nzdapplication.ui.custom.adapter.SearchAdapter;
import com.sls.nzdapplication.util.DeviceUtils;
import com.sls.nzdapplication.util.Utils;
import com.sls.nzdapplication.util.UuidUtils;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import es.dmoral.toasty.Toasty;
import me.kareluo.ui.OptionMenu;
import me.kareluo.ui.OptionMenuView;
import me.kareluo.ui.PopupMenuView;

/**
 * 这个类是一个表箱的Activity，主要用于表箱的添加和编辑。
 *
 * */
public class MeterBoxActivity extends AppActivity implements CableWellPhotoView.OnclickPhotoListener, View.OnClickListener{
    NiceSpinner boxRowView,boxColView,boxCzView,boxSbztView;
    TextView boxMeterNumberView,boxTypeView;
    ImageView qxxxRight,qdsbRight,boxCodeRight,gotoMeterView;
    TextView boxSaveView;
    private ClearEditText boxQxxxView,boxQdsbView,boxXqdyView,boxCodeView;
    private String meterBoxId;
    private Double lat = 0.0;

    private Double lon = 0.0;
    private boolean isNew = true;

    private String areaId = "";

    private String type;

    private String clickEquipmentId;

    private String equipmentId;

    private DyEquipmentUtil dyEquipmentUtil;

    private MeterBoxUtil meterBoxUtil;

    private int number;

    private DyEquipmentLineUtil dyEquipmentLineUtil;

    private MeterUtil meterUtil;

    private String photoType;

    private CableWellPhotoView equipmentDkPhotoView;

    private CableWellPhotoView equipmentGbPhotoView;

    private CableWellPhotoView equipmentQtPhotoView;

    // 1.声明常量
    public static final int DEFAULT_VIEW = 0x22;
    private static final int REQUEST_CODE_SCAN = 0X01;

    private List<DyEquipment> dyEquipmentList;

    private int selectE = 0;

    PopWindow popupWindow,popupWindow1;

    private ImageView rtPEquipmentView;

    private SwitchEquipmentUtil switchEquipmentUtil;

    private String clickSwitchId = "";

    private SwitchUtil switchUtil;

    private int code = 1;

    private AutoCompleteTextView autoCompleteTextViewNameView,boxLatView,boxLonView;

    public static final String SD_APP_DIR_NAME = "NZDAPP";

    private String autopath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/" + SD_APP_DIR_NAME + "/"; // 外部SD卡上的根目录

    private String logPath = autopath+"log";

    static final List<String> sbztList = new ArrayList<>();
    static {

        sbztList.add("在运");
        sbztList.add("停运");
        sbztList.add("未投运");
    }

    static final List<String> bxczList = new ArrayList<>();
    static {
        bxczList.add("塑料");
        bxczList.add("铁");
        bxczList.add("不锈钢");
        bxczList.add("合金");
        bxczList.add("木质");
        bxczList.add("其他");
    }

    static final List<String> rowList = new ArrayList<>();
    static {
        rowList.add("1");
        rowList.add("2");
        rowList.add("3");
        rowList.add("4");
        rowList.add("5");
        rowList.add("6");
        rowList.add("7");
        rowList.add("8");
        rowList.add("9");
        rowList.add("10");
        rowList.add("11");
        rowList.add("12");
        rowList.add("13");
        rowList.add("14");
        rowList.add("15");
        rowList.add("16");
        rowList.add("17");
        rowList.add("18");
        rowList.add("19");
        rowList.add("20");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_meter_box;
    }

    @Override
    protected void initView() {
        autoCompleteTextViewNameView = findViewById(R.id.meter_name);
        boxCodeView = findViewById(R.id.meter_code);
        boxXqdyView = findViewById(R.id.meter_unit);
        boxQdsbView = findViewById(R.id.meter_qdsb);
        boxLatView = findViewById(R.id.equipment_lat);
        boxLonView = findViewById(R.id.equipment_lon);
        boxRowView = findViewById(R.id.meter_row);
        boxRowView.attachDataSource(rowList);
        boxColView = findViewById(R.id.meter_column);
        boxColView.attachDataSource(rowList);
        boxTypeView = findViewById(R.id.box_type);
        boxCzView = findViewById(R.id.box_cz);
        boxCzView.attachDataSource(bxczList);
        boxSbztView = findViewById(R.id.box_sbzt);
        boxSbztView.attachDataSource(sbztList);
        boxQxxxView = findViewById(R.id.box_qxxx);
        boxMeterNumberView = findViewById(R.id.meter_number);
        gotoMeterView = findViewById(R.id.add_meter);
        qxxxRight = findViewById(R.id.qxxx_right);
        qdsbRight = findViewById(R.id.qdsb_right);
        boxCodeRight = findViewById(R.id.meter_code_right);

        equipmentDkPhotoView = findViewById(R.id.equipment_dk_photo);
        equipmentDkPhotoView.setOnclickPhotoListener(this);

        equipmentGbPhotoView = findViewById(R.id.equipment_gb_photo);
        equipmentGbPhotoView.setOnclickPhotoListener(this);

        equipmentQtPhotoView = findViewById(R.id.equipment_qt_photo);
        equipmentQtPhotoView.setOnclickPhotoListener(this);

        dyEquipmentLineUtil = new DyEquipmentLineUtil(getApplicationContext());
        meterBoxUtil = new MeterBoxUtil(getApplicationContext());
        dyEquipmentUtil = new DyEquipmentUtil(getApplicationContext());
        meterUtil = new MeterUtil(getApplicationContext());
        switchUtil = new SwitchUtil(getApplicationContext());
        switchEquipmentUtil = new SwitchEquipmentUtil(getApplicationContext());

        boxSaveView = findViewById(R.id.save_box);

        qdsbRight.setOnClickListener(this);
        qxxxRight.setOnClickListener(this);
        boxCodeRight.setOnClickListener(this);
        gotoMeterView.setOnClickListener(this);
        boxSaveView.setOnClickListener(this);


    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if(null !=intent && intent.getStringExtra("equipmentId")!=null){
            isNew = false;
            equipmentId = intent.getStringExtra("equipmentId");
            MeterBox meterBox = meterBoxUtil.listOneMeterBox(equipmentId);
            autoCompleteTextViewNameView.setText(meterBox.getBoxCode()==null?"":meterBox.getBoxCode());

            boxXqdyView.setText(meterBox.getCellUnit()==null?"":meterBox.getCellUnit());
            DyEquipment ex = dyEquipmentUtil.listOneDyEquipment(meterBox.getPreviousEquipmentId());
            String sname = "";
            if(ex!=null){
                if(ex.getType().equals("配电箱")){
                    if(switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId).size()>0){
                        clickSwitchId = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId).get(0).getSid();
                        sname = switchUtil.listOneSwitch(clickSwitchId).getName();
                    }
                }
                boxQdsbView.setText(ex.getName()+sname);
                clickEquipmentId = meterBox.getPreviousEquipmentId();
            }

            boxCodeView.setText(meterBox.getBoxName()==null?"":meterBox.getBoxName());
            boxLonView.setText(meterBox.getLon()==null?"":String.valueOf(meterBox.getLon()));
            boxLatView.setText(meterBox.getLat()==null?"":String.valueOf(meterBox.getLat()));
            boxRowView.setText(meterBox.getRow()==0?"0":String.valueOf(meterBox.getRow()));
            boxColView.setText(meterBox.getColumn()==0?"0":String.valueOf(meterBox.getColumn()));
            boxTypeView.setText(meterBox.getType()==null?"":meterBox.getType());
            boxCzView.setText(meterBox.getMaterial()==null?"":meterBox.getMaterial());
            boxSbztView.setText(meterBox.getSbzt()==null?"":meterBox.getSbzt());
            boxQxxxView.setText(meterBox.getQxxx()==null?"":meterBox.getQxxx());
            boxMeterNumberView.setText(String.valueOf(meterUtil.queryMetersByBoxId(equipmentId).size()));
            areaId = meterBox.getAreaId();
        } else if(null !=intent && intent.getBundleExtra("params") != null){
            Bundle bundle = intent.getBundleExtra("params");
            lat = bundle.getDouble("lat");
            lon = bundle.getDouble("lon");
            type = bundle.getString("type");
            areaId = bundle.getString("lineId");
            clickEquipmentId = bundle.getString("clickE");
            clickSwitchId = bundle.getString("clickS");
            equipmentId = UuidUtils.getStringID();
            boxLatView.setText(String.valueOf(lat));
            boxLonView.setText(String.valueOf(lon));

            DyEquipment ex = dyEquipmentUtil.listOneDyEquipment(clickEquipmentId);
            if(ex!=null){
                boxQdsbView.setText(ex.getName());
            }

            if(meterBoxUtil.queryMeterBoxByLineIdTime(areaId).size()==0){
                code = 1;
            }else{
                MeterBox dye = meterBoxUtil.queryMeterBoxByLineIdTime(areaId).get(0);
                code = dye.getCode()+1;
            }

            autoCompleteTextViewNameView.setText("Jlx"+ Utils.getName(code));
            boxMeterNumberView.setText(String.valueOf(meterUtil.queryMetersByBoxId(equipmentId).size()));
        }

        equipmentDkPhotoView.initData("MeterBox",equipmentId,"dk");
        equipmentGbPhotoView.initData("MeterBox",equipmentId,"gb");
        equipmentQtPhotoView.initData("MeterBox",equipmentId,"qt");

        List<MeterBox> meterBoxList = meterBoxUtil.queryMeterBoxByLineId(areaId);
        List<String> names = new ArrayList<>();
        for(MeterBox meterBox:meterBoxList){
            names.add(meterBox.getBoxCode());
        }

        SearchAdapter<String> arrayAdapter = new SearchAdapter<String>(MeterBoxActivity.this, android.R.layout.simple_dropdown_item_1line, names,SearchAdapter.ALL);
        autoCompleteTextViewNameView.setAdapter(arrayAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        boxMeterNumberView.setText(String.valueOf(meterUtil.queryMetersByBoxId(equipmentId).size()));
    }

    private void saveData(){
        String code = autoCompleteTextViewNameView.getText().toString();
        String unit = boxXqdyView.getText()==null?"":boxXqdyView.getText().toString();
        if(code.equals("")){
            Toasty.error(getApplicationContext(), "表箱号不能为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        if((meterBoxUtil.queryMeterBoxByLineIdAndCode(areaId,code).size()>0 && isNew) || (meterBoxUtil.queryMeterBoxByLineIdAndCode(areaId,code).size()>0 && !meterBoxUtil.queryMeterBoxByLineIdAndCode(areaId,code).get(0).getId().equals(equipmentId))){
            Toasty.error(getApplicationContext(), "表箱号已存在", Toast.LENGTH_LONG, true).show();
            return;
        }
//        if(unit.equals("")){
//            Toasty.error(getApplicationContext(), "小区单元不能为空", Toast.LENGTH_LONG, true).show();
//            return;
//        }
        if(!Utils.isNumeric(boxRowView.getText().toString())){
            Toasty.error(getApplicationContext(), "请正确输入行", Toast.LENGTH_LONG, true).show();
            return;
        }
        if(!Utils.isNumeric(boxColView.getText().toString())){
            Toasty.error(getApplicationContext(), "请正确输入列", Toast.LENGTH_LONG, true).show();
            return;
        }
        MeterBox meterBox;
        if(isNew){
            meterBox = new MeterBox();
        }else{
            meterBox = meterBoxUtil.listOneMeterBox(equipmentId);
        }
        meterBox.setId(equipmentId);
        meterBox.setBoxCode(code);
        meterBox.setBoxName(boxCodeView.getText()==null?"":boxCodeView.getText().toString());
        meterBox.setLat(Double.valueOf(boxLatView.getText().toString()));
        meterBox.setLon(Double.valueOf(boxLonView.getText().toString()));
        meterBox.setCellUnit(boxXqdyView.getText()==null?"":boxXqdyView.getText().toString());
        meterBox.setColumn(Integer.valueOf(boxColView.getText().toString()));
        meterBox.setRow(Integer.valueOf(boxRowView.getText().toString()));
        meterBox.setMaterial(boxCzView.getText().toString());
        meterBox.setType(boxTypeView.getText().toString());
        if(!isNew){
            if(!clickEquipmentId.equals(meterBox.getPreviousEquipmentId())){
                List<DyEquipmentLine> equipmentLines = dyEquipmentLineUtil.queryEquipmentLineByStartAndEnd(meterBox.getPreviousEquipmentId(),equipmentId);
                for(DyEquipmentLine dyEquipmentLine:equipmentLines){
                    dyEquipmentLineUtil.deleteDyEquipmentLine(dyEquipmentLine);
                }

                DyEquipmentLine equipmentLine = new DyEquipmentLine();
                equipmentLine.setId(UuidUtils.getStringID());
                equipmentLine.setStartEquipmentId(clickEquipmentId);
                equipmentLine.setEndEquipmentId(equipmentId);
                equipmentLine.setType("5");
                equipmentLine.setLineId(areaId);
                dyEquipmentLineUtil.insertDyEquipmentLine(equipmentLine);
            }
        }
        meterBox.setPreviousEquipmentId(clickEquipmentId);
        meterBox.setAreaId(areaId);
        meterBox.setSbzt(boxSbztView.getText().toString());
        meterBox.setQxxx(boxQxxxView.getText()==null?"":boxQxxxView.getText().toString());
        meterBox.setCode(this.code);
        if(meterBox.getRow()==1 && meterBox.getColumn()==1){
            meterBox.setType("单体表箱");
        }else{
            meterBox.setType("合体表箱");
        }
        meterBox.setCreateTime(new Date());
        boxTypeView.setText(meterBox.getType());
        if(isNew){
            meterBoxUtil.insertMeterBox(meterBox);
            DyEquipmentLine equipmentLine = new DyEquipmentLine();
            equipmentLine.setId(UuidUtils.getStringID());
            equipmentLine.setStartEquipmentId(clickEquipmentId);
            equipmentLine.setEndEquipmentId(equipmentId);
            equipmentLine.setType("5");
            equipmentLine.setLineId(areaId);
            dyEquipmentLineUtil.insertDyEquipmentLine(equipmentLine);
        }else{
            meterBoxUtil.updateMeterBox(meterBox);
        }

        if(!clickSwitchId.equals("")){
            List<SwitchEquipment> switchEquipments = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId);
            for(SwitchEquipment switchEquipment :switchEquipments){
                switchEquipmentUtil.deleteSwitchEquipment(switchEquipment);
            }
            SwitchEquipment switchEquipment = new SwitchEquipment();
            switchEquipment.setId(UuidUtils.getStringID());
            switchEquipment.setSid(clickSwitchId);
            switchEquipment.setEid(equipmentId);
            switchEquipmentUtil.insertSwitchEquipment(switchEquipment);
        }
        isNew = false;
        Toasty.success(getApplicationContext(), "保存成功", Toast.LENGTH_LONG, true).show();
    }

    private void openMenu(View view, List<OptionMenu> optionMenus, ClearEditText contentView){
        PopupMenuView menuView = new PopupMenuView(getApplicationContext());
        menuView.setMenuItems(optionMenus);
        menuView.setOrientation(LinearLayout.VERTICAL);
        menuView.setOnMenuClickListener(new OptionMenuView.OnOptionMenuClickListener() {
            @Override
            public boolean onOptionMenuClick(int position, OptionMenu menu) {
                contentView.setText(menu.getTitleRes());
                return true;
            }
        });

        menuView.show(view);
    }

    // 3.重写onRequestPermissionsResult方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (requestCode == DEFAULT_VIEW) {
            // 在调用第三方库前先执行下面代码
            Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    // 这里就可以捕获到第三方库的异常了
                    Utils.writeTxtToFile(e.getMessage(),logPath,"/log.txt");
                }
            });

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //申请权限之后，调用DefaultView扫码界面
                        ScanUtil.startScan(MeterBoxActivity.this, REQUEST_CODE_SCAN, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());
                    }catch (Exception e){
                        Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
                        Utils.writeTxtToFile(e.getMessage(),logPath,"/log.txt");
                    }
                }
            }).start();

        }

    }

    @Override
    public void onClick(View view) {
        if(view == qxxxRight){
            openMenu(qxxxRight, Arrays.asList(new OptionMenu(R.string.qxxx_1),new OptionMenu(R.string.qxxx_2),new OptionMenu(R.string.qxxx_3),
                    new OptionMenu(R.string.qxxx_5),new OptionMenu(R.string.qxxx_6),new OptionMenu(R.string.qxxx_7),
                    new OptionMenu(R.string.qxxx_8),new OptionMenu(R.string.qxxx_9),new OptionMenu(R.string.qxxx_10),
                    new OptionMenu(R.string.qxxx_11),new OptionMenu(R.string.qxxx_12),new OptionMenu(R.string.qxxx_13),
                    new OptionMenu(R.string.qxxx_14),new OptionMenu(R.string.qxxx_15),new OptionMenu(R.string.qxxx_16),new OptionMenu(R.string.qxxx_17)),boxQxxxView);
        }
        if(view == gotoMeterView){
            if(null == meterBoxUtil.listOneMeterBox(equipmentId)){
                Toasty.error(getApplicationContext(), "请先保存电表箱数据", Toast.LENGTH_LONG, true).show();
                return;
            }
            Intent intent = new Intent(MeterBoxActivity.this,DbDetailActivity.class);
            intent.putExtra("boxId",equipmentId);
            startActivity(intent);
        }
        if(view == boxSaveView){
            saveData();
        }
        if(view == qdsbRight){
            initProject();
        }
        if(view == boxCodeRight){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getActivity().requestPermissions(
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                        DEFAULT_VIEW);
            }
        }
    }


    @Override
    public void onClickPhotoListener(String type) {
        photoType = type;
    }

    @Override
    public void openPhotoView(String path) {
        Intent intent = new Intent(MeterBoxActivity.this,PhotoDetailActivity.class);
        intent.putExtra("filePath",path);
        startActivity(intent);
    }

    private void delData(){
        List<Meter> meterList = meterUtil.queryMetersByBoxId(equipmentId);
        for(Meter meter:meterList){
            meterUtil.deleteMeter(meter);
        }
        List<DyEquipmentLine> lines = dyEquipmentLineUtil.queryEquipmentLineByEid(equipmentId);
        for(DyEquipmentLine dyEquipmentLine:lines){
            dyEquipmentLineUtil.deleteDyEquipmentLine(dyEquipmentLine);
        }

        List<SwitchEquipment> switchEquipments = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId);
        for(SwitchEquipment switchEquipment:switchEquipments){
            switchEquipmentUtil.deleteSwitchEquipment(switchEquipment);
        }
        meterBoxUtil.deleteMeterBox(meterBoxUtil.listOneMeterBox(equipmentId));
        this.finish();
    }

    /**
     * 初始化所有设备
     * */
    private void initProject(){
        dyEquipmentList = dyEquipmentUtil.queryDyEquipmentByAreaIdIngd(areaId);
        List<String> projName = new ArrayList<>();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,500);
        List<DyEquipment> list = dyEquipmentList;
        ListView listView = new ListView(getApplicationContext());
        listView.setLayoutParams(layoutParams);
        for(DyEquipment dyEquipment:list){
            projName.add(dyEquipment.getName());
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(dyEquipmentList.get(i).getId().equals(equipmentId)){
                    Toasty.error(getApplicationContext(), "不能选择当前设备", Toast.LENGTH_LONG, true).show();
                }else{
                    selectE = i;
                    clickEquipmentId = dyEquipmentList.get(i).getId();
                    if(dyEquipmentList.get(i).getType().equals("配电箱")){
                        initSwitch();
                    }else{
                        boxQdsbView.setText(dyEquipmentList.get(i).getName());
                    }
                    popupWindow.dismiss();
                }

            }
        });
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_list_item_1, projName);
        listView.setAdapter(adapter);
        popupWindow= new PopWindow.Builder(MeterBoxActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("请选择前端设备")
                .addContentView(listView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();

    }

    /**
     * 初始化开关
     *
     * */
    private void initSwitch(){
        List<Switch> switchList = switchUtil.querySwitchByeId(clickEquipmentId);
        List<String> sName = new ArrayList<>();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,500);
        ListView listView = new ListView(getApplicationContext());
        listView.setLayoutParams(layoutParams);
        for(Switch sw:switchList){
            sName.add(sw.getName());
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                clickSwitchId = switchList.get(i).getId();
                boxQdsbView.setText(dyEquipmentList.get(selectE).getName()+switchList.get(i).getName());
                popupWindow1.dismiss();


            }
        });
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_list_item_1, sName);
        listView.setAdapter(adapter);
        popupWindow1 = new PopWindow.Builder(MeterBoxActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("请选择开关")
                .addContentView(listView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();

    }

    @Override
    public void onRightClick(View view) {
        new PopWindow.Builder(this)
                .setStyle(PopWindow.PopWindowStyle.PopUp)
                .setTitle("你确定要删除当前数据！！")
                .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        delData();
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //从onActivityResult返回data中，用 ScanUtil.RESULT作为key值取到HmsScan返回值
        if (requestCode == REQUEST_CODE_SCAN) {
            Object obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj instanceof HmsScan) {
                if (!TextUtils.isEmpty(((HmsScan) obj).getOriginalValue())) {
                    if(meterBoxUtil.queryMeterBoxByLineIdAndName(areaId,((HmsScan) obj).getOriginalValue()).size()==0 ){
                        boxCodeView.setText(((HmsScan) obj).getOriginalValue());
                    }else{
                        Toasty.warning(getApplicationContext(), "该电表已存在", Toast.LENGTH_LONG, true).show();
                    }
                }
                return;
            }
        }else{
            if(photoType.equals("dk")) {
                equipmentDkPhotoView.onActivityResultListener(requestCode, resultCode, data);
            }
            if(photoType.equals("gb")) {
                equipmentGbPhotoView.onActivityResultListener(requestCode, resultCode, data);
            }
            if(photoType.equals("qt")) {
                equipmentQtPhotoView.onActivityResultListener(requestCode, resultCode, data);
            }
        }
    }
}